package com.hcc.flow.server.common.utils;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.SocketException;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPReply;

public class FtpUntil {

	static Log logger = LogFactory.getLog(FtpUntil.class);
	// 账号
	private static String username = "jklz";
	// 密码
	private static String password = "jklz";
	// 地址
	private static String ip = "192.168.0.154";
	// 端口号
	private static String port = "21";

	/**
	 * ftp链接
	 * 
	 * @param ip       ftp地址
	 * @param username 账号
	 * @param password 密码
	 * @return
	 * @throws IOException
	 */
	private static FTPClient ftpConnection() throws IOException {
		FTPClient ftpClient = new FTPClient();
		try {
			ftpClient.connect(ip, Integer.parseInt(port));
			ftpClient.login(username, password);
			int replyCode = ftpClient.getReplyCode(); // 是否成功登录服务器
			if (!FTPReply.isPositiveCompletion(replyCode)) {
				ftpClient.disconnect();
				logger.error("--ftp连接失败--");
				System.exit(1);
			}
			ftpClient.enterLocalPassiveMode();// 这句最好加告诉对面服务器开一个端口
		} catch (SocketException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return ftpClient;
	}

	/**
	 * 下载方法
	 * 
	 * @param ftpClient   FTPClient对象
	 * @param newFileName 新文件名
	 * @param fileName    原文件名
	 * @param downUrl     下载路径
	 * @return
	 * @throws IOException
	 */
	public static File downFile(String fileName)
			throws IOException {
		FTPClient ftpClient=ftpConnection();
		String[] strList=fileName.split("/");
		String newFileName=strList[strList.length-1];
		OutputStream os = null;
		File localFile = new File(newFileName);
		os = new FileOutputStream(localFile);
		ftpClient.retrieveFile(new String(fileName.getBytes(), "ISO-8859-1"), os);
		os.close();
		close(ftpClient);
		return localFile;
	}

	/**
	 * 断开FTP连接
	 * 
	 * @param ftpClient 初始化的对象
	 * @throws IOException
	 */
	private static void close(FTPClient ftpClient) throws IOException {
		if (ftpClient != null && ftpClient.isConnected()) {
			ftpClient.logout();
			ftpClient.disconnect();
		}
	}
}